<?php
/**
 * LoginAccountService.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-18 00:05:38
 * @modified    2023-02-18 00:05:38
 *
 */

namespace App\Services;

use App\Helpers\Jwt;

class LoginAccountService extends BaseService
{
    // token前缀，jwt验证带该前缀则是前台用户，否则是后台用户(后台ID为数字，手机号码也为数字，防止ID和手机号码重复出现验证错误)
    const ACCOUNT_PREFIX = 'account_';
    public function login()
    {
        $account = request()->get('account');
        $verifyCode = trim(request()->get('verify_code') ?? '');
        if (!verify_telephone($account)) {
            throw new \Exception('手机号码格式错误');
        }
        if (!$verifyCode) {
            throw new \Exception('请输入验证码');
        }
        try {
            $verifyCodeService = new VerifyCodeService($account);
            $verifyCodeService->validateCode($verifyCode);
            $jwt = new Jwt();
            $tokenAccount = self::ACCOUNT_PREFIX . $account;
            $token = $jwt->getToken($tokenAccount);
            return ['access_token' => $token];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}